<template>
  <div class="body_bgi full relative">
    <!-- 活动已开始 -->
    <div class="w_full h_300 text_center absolute_center p_20" v-if="!isActivityStart">
      <div class="fs_22">欢迎您参与本次活动</div>
      <div class="fs_22 mt_30">请等待活动开始</div>

      <div class="mt_50">
        <van-button round block type="primary" @click="clickStartActivity()">开始评分</van-button>
      </div>
    </div>

    <!-- 活动已开始 -->
    <div class="full" v-if="isActivityStart">
      <div class="w_full text_center fs_22 p_20">
        参赛羊编号
        <div class="font_number fs_70 pv_20 color_orange" v-if="sheepInfo && sheepInfo.id">{{ sheepInfo.sheepNumber }}</div> 
      </div>

      <van-form v-if="!isScore">
        <van-field
          readonly
          clickable
          name="密度"
          label="密度："
          label-width="100"
          :value="scoreForm.density"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('density')"
          :rules="[{required: true }]"
        />
        <div class="mb_20"></div>
        <van-field
          readonly
          clickable
          name="弯曲度"
          label="弯曲度："
          label-width="100"
          :value="scoreForm.wanQu"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('wanQu')"
          :rules="[{required: true }]"
        />
        <div class="mb_20"></div>
        <van-field
          v-model="scoreForm.xiDu"
          type="number"
          name="细度"
          label="细度："
          label-width="100"
          input-align="left"
          :disabled="isScore"
          placeholder="请填写分数 (8 ~ 32)"
          :rules="[{ validator: valideValue, required: true, message: '请输入 8 ~ 32 数值' }]"
        />
        <div class="mb_20"></div>
        <van-field
          readonly
          clickable
          name="油汗"
          label="油汗："
          label-width="100"
          :value="scoreForm.oilSweat"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('oilSweat')"
          :rules="[{required: true }]"
        />
        <div class="mb_20"></div>
        <van-field
          readonly
          clickable
          name="均匀度"
          label="均匀度："
          label-width="100"
          :value="scoreForm.uniformity"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('uniformity')"
          :rules="[{required: true }]"
        />
        <div class="mb_20"></div>
        <van-field
          readonly
          clickable
          name="腹毛"
          label="腹毛："
          label-width="100"
          :value="scoreForm.fuMao"
          :disabled="isScore"
          placeholder="请选择分数"
          @click="selectValue('fuMao')"
          :rules="[{required: true }]"
        />
        <div class="mb_20"></div>
        <van-popup v-model="isShowPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="[0, 1, 2, 3, 4]"
            @confirm="confirmPicker"
            @cancel="isShowPicker = false"
          />
        </van-popup>

        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" @click="clickSubmit()">提交评分</van-button>
        </div>
      </van-form>

      <!-- 提交完成后 等待评分 -->
      <div class="w_full h_full-350 mt_20" v-else>
        <div class="w_full h_50 lh_50 text_center fs_22">评分结果</div>

        <div class="w_full h_full-200 scroll_box overflow_y_auto">
          <div class="w_full h_60 lh_60 border_b_1_s_eee" v-for="(item, index) in scoreList" :key="index">
            <div class="w_full flex_row_between ph_30 bgc_orange color_fff fs_22" v-if="item && item.id == my.id">
              <div>{{ index + 1 }}</div>
              <div>我</div>
              <div>评分：{{ item.totalScore }} </div>
            </div>

            <div class="w_full flex_row_between ph_30 fs_22" v-else>
              <div>{{ index + 1 }}</div>
              <div>评委: {{ item.id }} </div>
              <div>评分：{{ item.totalScore }} </div>
            </div>
          </div>
        </div>

        <div class="w_full h_100 lh_100 p_20">
          <van-button round block type="primary" :disabled="scoreList.length < 2" @click="nextSheep()">下一个</van-button>
        </div>
      </div>
    </div>
    
    <van-dialog v-model="isShowDialog" title="确认提交评分？" show-cancel-button @confirm="submitScoreForm">
      <div class="w_full ph_10 mv_20 fs_22">
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">密度：</div>
          <div class="w_50_p pl_5">{{ scoreForm.density }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">弯曲度：</div>
          <div class="w_50_p pl_5">{{ scoreForm.wanQu }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">细度：</div>
          <div class="w_50_p pl_5">{{ scoreForm.xiDu }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">油汗：</div>
          <div class="w_50_p pl_5">{{ scoreForm.oilSweat }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">均匀度：</div>
          <div class="w_50_p pl_5">{{ scoreForm.uniformity }}</div>
        </div>
        <div class="w_full flex_row_start pb_10">
          <div class="w_50_p pr_5 text_right">腹毛：</div>
          <div class="w_50_p pl_5">{{ scoreForm.fuMao }}</div>
        </div>
      </div>
    </van-dialog> 
  </div>
</template>

<script>
  import {
    getCurrentSheep,
    saveSheepScore,
    getSheepScoreDetail
  } from '@/api/index.js'

  import { Toast, Dialog } from 'vant';

  export default {
    name: 'SheepScore',
    data() {
      return {
        isActivityStart: false,

        activeFormItem: null,

        isShowPicker: false,

        scoreForm: {
          density: '1',
          wanQu: '1',
          xiDu: '23',
          oilSweat: '1',
          uniformity: '1',
          fuMao: '1'
        },
        
        contestId: null,
        roomId: null,
        sheepInfo: {},

        isScore: false,
        isShowDialog: false,

        my: null,
        scoreList: [],

        timer: null
      }
    },
    
    async mounted() {
      let contestId = this.$route.params.contestId
      let roomId = this.$route.params.roomId

      this.contestId = contestId
      this.roomId = roomId

      // 获取 房间中的 当前羊
      // this.getCurrentSheep(roomId)
    },

    destroyed() {
      clearInterval(this.timer)
    },

    methods: {
      // 点击 开始 评分
      clickStartActivity() {
        this.getCurrentSheep(this.roomId)
        if (!this.isActivityStart) {
          Toast.loading({
            duration: 2000,
            message: '请等待羊登场'
          })
        } else {
          Toast.success({
            duration: 2000,
            message: '请开始评分'
          })
        }
      },

      // 获取 房间中的 当前羊
      async getCurrentSheep(roomId, sheepNumber) {
        let res = await getCurrentSheep(roomId)
        try {
          if (res.code == 1000 && res.data) {
            this.isActivityStart = true
            
            // 初始化评分 表单
            this.initScore()

            if (sheepNumber) {
              if (res.data.sheepNumber != sheepNumber) {
                this.sheepInfo = res.data
              } 
            } else {
              this.sheepInfo = res.data
            }

            if (res.data.isScore) {
              this.isScore = res.data.isScore

              // 获取 评分详情
              this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)

              this.timer = setInterval(() => {
                // 获取 评分详情
                this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)
              }, 2000)
            }
          } else {
            this.isActivityStart = false
            this.sheepInfo = {}
          }
        } catch(err) {
          console.log('获取房间中的当前羊失败 : ', err);
        }
      },

      // 校验输入的 值
      valideValue(val) {
        return 8 <= val && val <= 32
      },

      // 选择 值
      selectValue(form) {
        this.activeFormItem = form
        this.isShowPicker = true
      },

      // 确认 弹出层 值
      confirmPicker(val) {
        this.scoreForm[this.activeFormItem] = val
        this.isShowPicker = false
      },

      // 点击【提交】按钮， 显示确认框
      clickSubmit() {
        let validateResult = this.validateScoreForm()

        validateResult ? this.isShowDialog = true : Toast.fail('请检查表单！');
      },

      // 验证表单 内容
      validateScoreForm() {
        let result = ''
        for (let i in this.scoreForm) {
          // console.log('验证 : ', );
          if (this.scoreForm[i] === '') {
            result = false
            return 
          } else {
            result = true
          }
        }

        return result
      },

      // 点击 【确定】
      submitScoreForm() {
        let params = {
          contestId: parseInt(this.contestId),
          rfid: this.sheepInfo.rfid,
          roomId: parseInt(this.roomId),
          density: parseInt(this.scoreForm.density),
          wanQu: parseInt(this.scoreForm.wanQu),
          xiDu: parseInt(this.scoreForm.xiDu),
          oilSweat: parseInt(this.scoreForm.oilSweat),
          uniformity: parseInt(this.scoreForm.uniformity),
          fuMao: parseInt(this.scoreForm.fuMao)
        }

        this.saveSheepScore(params)
      },

      // 提交评分
      async saveSheepScore(params) {
        let res = await saveSheepScore(params)
        try {
          if (res.code == 1000 && res.message == 'success') {
            Toast.success('提交成功！');
            this.isScore = true

            // 获取 评分详情
            this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)

            this.timer = setInterval(() => {
              // 获取 评分详情
              this.getSheepScoreDetail(this.contestId, this.sheepInfo.rfid)
            }, 2000)
          }
        } catch(err) {
          console.log('羊评分提交失败 : ', err);
        }
      },

      // 获取 羊 评分详情
      async getSheepScoreDetail(contestId, rfid) {
        let res = await getSheepScoreDetail(contestId, rfid)
        try {
          if (res.code == 1000 && res.message == 'success') {
            this.my = res.data.mySheepScore
            this.scoreList = res.data.sheepScoreList

            // 评委 数量
            if (res.data.sheepScoreList && res.data.sheepScoreList.length == 2) {
              clearInterval(this.timer)
            }                       
          }
        } catch(err) {
          console.log('获取羊的评分信息失败 : ', err);
        }
      },

      // 评委 手动切换 当前羊
      nextSheep() {
        this.isScore = false
        this.getCurrentSheep(this.roomId, this.sheepInfo.sheepNumber)
      },

      // 初始化 评分表单
      initScore() {
        this.scoreForm = {
          density: '',
          wanQu: '',
          xiDu: '',
          oilSweat: '',
          uniformity: '',
          fuMao: '',
        }

        this.my = null
        this.scoreList = []
      },

      // 倒计时
      countDown() {
        const toast = Toast.loading({
          duration: 0, 
          forbidClick: true,
          message: '',
        });

        let second = 3;
        const timer = setInterval(() => {
          if (second) {
            toast.message = `${second} 秒后更新`;
            second--;
          } else {
            clearInterval(timer);
            // 手动清除 Toast
            Toast.clear();

            this.isScore = false
          }
        }, 1000);
      },
    }
  }
</script>

<style>
  .van-cell__title > span { font-size: 20px !important; }
  .van-cell { padding: 20px 10px; }
  .van-field__body > input { font-size: 20px !important; }
  .van-dialog__header { font-size: 22px !important; }
  .van-button__text { font-size: 22px !important; }
</style>